<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import axios from '../axios';
import { router } from '../router'
import { roleTypeToString } from '../model';

const formRef = ref<FormInstance>()

const formData = reactive({
    username: '',
    password: '',
})

const onSubmit = async () => {
    if (formData.username == '') {
        ElMessage({
            type: 'error',
            message: '请输入用户名'
        })
        return 
    }
    if (formData.password == '') {
        ElMessage({
            type: 'error',
            message: '请输入密码'
        })
        return 
    }
    const res = await axios.post('/login', {
        username: formData.username,
        password: formData.password,
    })
    

    if (!res.data['ok']) {
        ElMessage({
            type: 'error',
            message: res.data['msg']
        })
        return
    }

    const role = roleTypeToString(res.data['user']['role'])

    ElMessage({
        type: 'success',
        message: `欢迎回来, ${role} ${res.data['user']['nickname']}`
    })

    router.push('/home')
}
</script>

<template>
<div class="outer">
  <el-card class="card">
<div class="warp">
    <h1 class="title">
        在线申请及审批系统
    </h1>
    <el-form
        ref="formRef"
        label-position="top"
        style="width: 300px; margin-bottom: 20px;"
    >
        <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" @keyup.enter.native="onSubmit">
            <el-input v-model="formData.password" show-password></el-input>
        </el-form-item>
        <el-form-item align="middle">
            <el-col>
                <div class="link">
                    <el-link type="info" href="/register">注册</el-link>
                </div>
            </el-col>
        </el-form-item>
        <el-form-item align="middle">
            <el-col>
                <el-button size="large"  @click="onSubmit" style="width: 200px;">登录</el-button>
            </el-col>
        </el-form-item>

    </el-form>
</div>
</el-card>
</div>
</template>

<style scoped>
.card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);;
}

.warp {
  display: flex;
  flex-direction: column;

  align-items: center;
  justify-content: center;
}

.link {
  display: flex;
  align-items: center;
  justify-content: end;
}

h1 {
  color: var(--el-text-color-primary);
  margin-bottom: 60px;
}
.el-card {
  display: flex;
  justify-content: center;
  align-items: center;

  width: 500px;
}

.outer {
  display: flex;
  width: 100%;
  height: 100%;
  justify-content: center;
  align-items: center;
}
</style>